<script lang="jsx" setup>
import { ref, watch } from 'vue';
import { message } from 'ant-design-vue';
import Modal from '@/components/common/modal.vue';
import { editShadaiNum } from '@/service/api/modules/grinding-plate-edit/edit';
import Form from '@/components/common/form.vue';
const props = defineProps({
  visible: {
    type: Boolean,
    default: () => false
  }
});

const emit = defineEmits(['close', 'addSuccess']);

const topFormList = ref([
  {
    type: 'input',
    key: 'sandScrubbTime',
    label: '累计使用砂带数',
    span: 24
  }
]);

const modelVisible = ref(props.visible);
const modleAddLoading = ref(false);

const topFormRef = ref(null);

const model = ref(getModel(topFormList.value));

function getModel(arr) {
  const obj = {};
  arr.forEach(item => {
    if (item.key) {
      obj[item.key] = null;
    }
  });
  console.log('obj :>> ', obj);
  return obj;
}

async function handleOk() {
  const form = { ...topFormRef.value };
  await form.validateForm();
  modleAddLoading.value = true;
  console.log(model.value.sandScrubbTime);

  // try {
  //   const { error } = await editShadaiNum({
  //     num: model.value.sandScrubbTime
  //   });
  // } catch (error) {
  //   console.log(error);
  //   if (!error) {
  //     console.log('修改成功');
  //     console.log(num);
  //     message.success('修改累计使用砂带数成功!');
  //     handleClose();
  //     emit('addSuccess');
  //   }
  // } finally {
  //   modleAddLoading.value = false;
  // }

  try {
    const { error } = await editShadaiNum({
      num: model.value.sandScrubbTime
    });
    if (!error) {
      console.log('修改成功');
      message.success('修改累计使用砂带数成功!');
      handleClose();
      emit('addSuccess');
    } else {
      message.error('修改累计使用砂带数失败!'); // 当有错误时显示失败信息
    }
  } catch (err) {
    console.log(err); // 打印错误信息
    message.error('修改累计使用砂带数失败!'); // 基于错误提示显示消息
  } finally {
    modleAddLoading.value = false;
  }
}

function handleClose() {
  modelVisible.value = false;
  model.value = getModel(topFormList.value);
  emit('close');
}

watch(
  () => props.visible,
  val => {
    modelVisible.value = val;
  }
);
</script>

<template>
  <Modal
    v-model:visible="modelVisible"
    title="修改累计使用砂带数"
    height="260px"
    width="500px"
    :destroy-on-close="true"
    :centered="true"
    @close="handleClose"
  >
    <div class="edit-shadai-form" style="padding: 15px 20px">
      <Form ref="topFormRef" v-model:model="model" :form-list="topFormList"></Form>
    </div>

    <template #footer>
      <div class="modal-footer">
        <AButton type="primary" :loading="modleAddLoading" @click="handleOk">修 改</AButton>
        <AButton @click="handleClose">关 闭</AButton>
      </div>
    </template>
  </Modal>
</template>

<style lang="scss" scoped></style>
